// pages/interface/index.js
Page({
  data: {
    books: [],
    // 定义数据
    keyword: "",
    history: wx.getStorageSync("history") || [],
  },
  // 1. 获取图书列表
  getBooks() {
    // 1.1 开启loading
    wx.showLoading({
      title: "正在拼命加载中...",
      mask: true,
    });

    // 1.2 发送网络请求
    wx.request({
      url: "https://hmajax.itheima.net/api/books",
      data: {
        creator: "zhangsan",
      },
      method: "GET",
      success: (res) => {
        this.setData(
          {
            books: res.data.data,
          },
          () => {
            wx.showToast({
              title: "获取书单成功~",
              duration: 2000,
              mask: true,
              icon: "none",
            });
          }
        );
        console.log(this.data.books);
      },
      fail: (err) => {},
      complete: (res) => {
        wx.hideLoading();
      },
    });
  },

  // 2. 展示模态框
  showModel() {
    wx.showModal({
      title: "温馨提示",
      content: "您确定要删除吗?",
      complete: (res) => {
        if (res.cancel) {
        }

        if (res.confirm) {
        }
      },
    });
  },

  // 3. 展示抽屉弹层
  showActionSheet() {
    wx.showActionSheet({
      itemList: ["A", "B", "C", "D"],
    });
  },

  // 4. 数据持久化
  async saveData() {
    // wx.setStorageSync("token", "udwqhwqjdwqj98988");
    // wx.setStorageSync("user", { name: "张三", age: 18, sex: "男" });

    await wx.setStorage({
      key: "token",
      data: "66666666666",
    });
  },
  readData() {
    wx.showToast({
      title: wx.getStorageSync("token"),
    });
  },
  removeData() {
    wx.removeStorageSync("token");
  },
  clearData() {
    wx.clearStorageSync();
  },

  // 5. 选择图片
  choosePhoto() {
    wx.chooseMedia({
      count: 9,
      mediaType: ["mix"],
      sourceType: ["album", "camera"],
      success: (res) => {
        console.log(res);
      },
      fail: (error) => {
        console.log(error);
      },
      complete: () => {
        console.log("来了");
      },
    });
  },

  async choosePhoto1() {
    try {
      const res = await wx.chooseMedia({
        count: 9,
        mediaType: ["mix"],
        sourceType: ["album", "camera"],
      });
      console.log(res);
    } finally {
      console.log("66666");
    }
  },

  // 6. 点击搜索
  onSearch() {
    // 6.1 判断是否为空
    if (this.data.keyword.trim() === "") {
      wx.showToast({
        title: "请输入搜索内容",
        icon: "none",
      });
      return;
    }
    // 6.2 把数据加入数组
    const temp = this.data.history;
    temp.unshift(this.data.keyword);
    this.setData(
      {
        history: temp,
        // 清空输入框
        keyword: "",
      },
      () => {
        wx.setStorageSync("history", this.data.history);
      }
    );
  },

  // 7. 清空
  onClear() {
    this.setData(
      {
        history: [],
      },
      () => {
        wx.removeStorageSync("history");
      }
    );
  },

  clickMeOne(event) {
    console.log(event.target.dataset);
  },

  clickMeTwo(event) {
    console.log(event.mark);
  },
});
